package com.haixiaoke.saas.common.utils;

import cn.hutool.core.util.HexUtil;
import cn.hutool.json.JSONUtil;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * @Author Dell
 * @Date 2023/8/7
 **/
public class RequestAesUtils {

    public static final String KEY = "e75e2d3126357d031ddaf412f9110f66";

    /**
     * 加密
     *
     * @param str
     * @return
     */
    public static String encrypt(String str) {
        String jsonStr = JSONUtil.toJsonStr(str);

        // 对返回加密;
        byte[] encrypted = null;
        try {
            byte[] raw = KEY.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            encrypted = cipher.doFinal(jsonStr.getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return HexUtil.encodeHexStr(encrypted);
    }

    /**
     * 解密
     *
     * @param str
     * @return
     */
    public static String decrypt(String str) {
        try {
            // 判断Key是否正确
            /*if (key == null) {
                System.out.print("Key为空null");
                return;
            }
            // 判断Key是否为16位
            if (key.length() != 16) {
                System.out.print("Key长度不是16位");
                return;
            }*/
            byte[] raw = KEY.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
//            byte[] encrypted1 = new Base64().decode(sSrc);//先用base64解密
            try {
                byte[] ss = HexUtil.decodeHex(str);
                // content.getBytes(StandardCharsets.UTF_8)下方的参数
                byte[] original = cipher.doFinal(ss);
                String originalString = new String(original, StandardCharsets.UTF_8);
                System.out.println("originalString = " + originalString);
                return originalString;
            } catch (Exception e) {
                System.out.println(e.toString());
                System.out.println("解码失败！！！！");
            }
        } catch (Exception ex) {
            System.out.println(ex.toString());
        }

        return null;
    }
}
